<template>
    <div class="content">
        <!-- <div class="title">
            <span>任务统计</span>
            <div class="btn-operate">
                <el-button
                    v-for="item in actualSponsors"
                    :type="item.userCode == currentUserCode ? 'primary' : ''"
                    :key="item.userCode"
                    :value="item.userCode"
                    @click="handleSponsor(item.userCode)"
                >
                    {{ item.sponsor }}
                </el-button>
            </div>
        </div>
        <el-divider></el-divider> -->
        <div class="charts">
            <div class="charts-part1">
                <div v-for="item in cards" :key="item.title" class="charts-part1-content">
                    <div class="card-title">
                        <span>{{ item.title }}</span>
                    </div>
                    <TaskBarChart
                        :data="{
                            ...item,
                            xData: taskXData,
                            type: 'stastics-pending',
                        }"
                        :ref="item.name"
                        @click-bar="barClick(item.name, $event)"
                        class="chart1-bar"
                    ></TaskBarChart>
                </div>

                <div class="already-statistics">
                    <div class="alr-chart">
                        <div class="card-title">
                            <span>{{ alrData.title }}</span>
                            <div class="operate">
                                <el-button :type="bgcColor.week ? 'primary' : 'text'" size="mini" @click="handleAlready('week')">本周</el-button>
                                <!-- <el-button :type="bgcColor.year ? 'primary' : 'text'" size="mini">年度</el-button>
                                <el-date-picker
                                    v-model="alrParams.year"
                                    @change="handleAlready('year')"
                                    type="year"
                                    size="mini"
                                    placeholder="选择年"
                                    style="width:75px"
                                    value-format="yyyy"
                                    format="yyyy"
                                >
                                </el-date-picker> -->

                                <el-button :type="!bgcColor.week ? 'primary' : 'text'" size="mini">
                                    <el-dropdown placement="bottom-start" trigger="click" @command="handleSelectField">
                                        <span style="cursor: pointer">
                                            {{ selectByField == 'month' ? '月度' : '年度' }}<i class="el-icon-arrow-down el-icon--right"></i>
                                        </span>
                                        <el-dropdown-menu slot="dropdown">
                                            <el-dropdown-item
                                                :command="item.value"
                                                v-for="item in [
                                                    { text: '年度', value: 'year' },
                                                    { text: '月度', value: 'month' },
                                                ]"
                                                :key="item.value"
                                                >{{ item.text }}</el-dropdown-item
                                            >
                                        </el-dropdown-menu>
                                    </el-dropdown></el-button
                                >
                                <el-date-picker
                                    v-model="alrParams.year"
                                    @change="handleAlready('year')"
                                    type="year"
                                    size="mini"
                                    placeholder="选择年"
                                    style="width:95px"
                                    value-format="yyyy"
                                    format="yyyy年"
                                    v-if="selectByField == 'year'"
                                >
                                </el-date-picker>
                                <el-date-picker
                                    v-model="alrParams.month"
                                    @change="handleAlready('month')"
                                    type="month"
                                    size="mini"
                                    placeholder="选择月"
                                    style="width:95px"
                                    value-format="yyyyMM"
                                    format="yyyy年MM月"
                                    v-if="selectByField == 'month'"
                                ></el-date-picker>
                                <!-- <el-button type="primary" size="mini" @click="handleSearch('alr')">查询</el-button> -->
                            </div>
                        </div>

                        <TaskBarChart
                            :data="{ ...alrData, type: 'already-statistics' }"
                            ref="already-statistics"
                            @click-bar="barClick('already-statistics', $event)"
                            class="chart1-bar"
                        ></TaskBarChart>
                    </div>
                </div>
            </div>
            <div style="flex: 1;background-color: #fff;margin-top: 10px;">
                <div class="title">
                    <span>合同/协议统计</span>
                    <div class="btn-operate">
                        <el-button :type="contractHalfYearTime == '6' ? 'primary' : ''" size="mini" @click="handleSearch('contract', '6')"
                            >近6月</el-button
                        >
                        <el-button :type="contractHalfYearTime == '12' ? 'primary' : ''" size="mini" @click="handleSearch('contract', '12')"
                            >近12月</el-button
                        >
                    </div>
                </div>
                <el-divider></el-divider>
                <div class="charts-part3">
                    <div class="contract-protocol">
                        <ContractBarChart
                            ref="contract-protocol"
                            :data="contractData"
                            @click-bar="barClick('contract-protocol', $event)"
                        ></ContractBarChart>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script lang="ts">
import { Vue, Component, Watch, Prop } from 'vue-property-decorator';
import ContractBarChart from './contract-bar-chart.vue';
import TaskBarChart from './task-bar-chart-plus.vue';
import * as api from '../api/fund-pending-manage';
import { getUser } from '@/utils/user-util';
import { uniqueFunc } from '@/utils/tools';
import moment from 'moment';
@Component({
    name: 'TaskStatisticsPlus',
    components: {
        TaskBarChart,
        ContractBarChart,
    },
})
// 视图
export default class TaskStatisticsPlus extends Vue {
    @Prop() activeValue: string;
    @Prop() currentUserCode: string;
    // currentUserCode: string = getUser().userCode;
    sponsors: any = [
        // {
        //     userCode: '122',
        //     sponsor: '小李',
        // },
        // {
        //     userCode: '123',
        //     sponsor: '小谭',
        // },
        // {
        //     userCode: '124',
        //     sponsor: '小陶',
        // },
    ];
    // userOptions: any = [{ userCode: '', userName: '' }];

    // 已办任务参数
    alrParams = {
        weekFlag: true,
        year: '',
        month: '',
        operator: '',
    };

    // 已办任务查询参数背景色
    bgcColor = {
        week: true,
        year: false,
        month: false,
    };
    selectByField: string = 'month';
    taskXData = ['产品募集', '已设立待备案', '产品运作'];

    contractHalfYearTime: string = '6'; // 6 近6月
    cards = [
        {
            title: '合规条款库维护',
            name: 'indicators',
            key: '1',
            data: [10, 20, 30],
        },
        {
            title: '交易系统维护',
            name: 'trades',
            key: '2',
            data: [10, 20, 30],
        },
        {
            title: '事后系统维护',
            name: 'afterwards',
            key: '3',
            data: [10, 20, 30],
        },
    ];

    contractData: any = {
        title: '合同/协议统计',
        xData: ['202301', '202302', '202303', '202304', '202305', '202306'],
        data: { products: [10, 20, 30, 40, 50, 60], protocols: [10, 20, 30, 40, 50, 60], totals: [20, 40, 60, 80, 100, 120] },
    };
    alrData: any = {
        xData: ['合规条款库', '交易系统', '事后系统'],
        data: [10, 20, 30, 40],
        title: '已办任务统计',
    };
    chartInstanceArr: any = [];
    chartComponent: any[] = ['indicators', 'trades', 'afterwards'];
    isFirst: boolean = true;
    @Watch('activeValue', { immediate: true })
    async handleActiveValue() {
        if (this.activeValue === 'task-statistics') {
            if (this.isFirst) {
                // try {
                //     await this.getUserOptions();
                // } finally {
                this.getProcessData();
                this.getContractHalfYear();
                this.getAlrData();
                this.isFirst = false;
                this.$nextTick(() => {
                    this.chartComponent.forEach(ele => {
                        console.log(this.$refs[ele] as any, '(this.$refs[ele] as any)');
                        this.chartInstanceArr.push((this.$refs[ele][0] as any).chartInstance);
                    });

                    this.chartInstanceArr.push((this.$refs['contract-protocol'] as any).chartInstance);
                    this.chartInstanceArr.push((this.$refs['already-statistics'] as any).chartInstance);

                    window.addEventListener('resize', this.screenAdapter);
                    this.screenAdapter();
                });
                // }
            } else {
                this.screenAdapter();
            }
        }
    }

    @Watch('currentUserCode', { immediate: true })
    changeSponsor(newData, oldData) {
        if (newData !== oldData && !this.isFirst) {
            this.getProcessData();
            this.getAlrData();
        }
    }
    // @Watch('contractHalfYearTime', { immediate: true })
    // handleContractHalfYearTime() {
    //     console.log('aaaaaaaaaaaa');
    //     this.getContractHalfYear();
    // }

    get actualSponsors() {
        this.sponsors.unshift({ userCode: '', sponsor: '全部' });
        return this.sponsors;
    }

    screenAdapter() {
        const titleFontSize = ((this.$refs['already-statistics'] as any).offsetWidth / 100) * 5.6;
        // 分辨率变化图表配置
        const adapterOption = {
            axisLabel: {
                textStyle: {
                    fontSize: titleFontSize,
                },
            },
            // 柱状条目
            series: [
                {
                    // barWidth: titleFontSize,
                    // 条目文字配置
                    // itemStyle: {
                    //   barBorderRadius: [titleFontSize / 2, titleFontSize / 2, 0, 0],
                    // }
                },
            ],
        };
        console.log(this.chartInstanceArr);
        this.chartInstanceArr.forEach(ele => {
            console.log(ele, 'ele');

            ele.setOption(adapterOption);
            // (this.$refs as any)['already-statistics'].extension(ele);
            ele.resize();
        });

        setTimeout(() => {
            this.chartInstanceArr.forEach(ele => {
                console.log(ele, 'ele2');
                ele.resize();
            });
        }, 500);
    }

    destroyed() {
        window.removeEventListener('resize', this.screenAdapter);
    }

    // 查询
    handleSearch(type: string, time?: string) {
        if (type == 'process') {
            this.getProcessData();
        } else if (type == 'contract') {
            if (time !== this.contractHalfYearTime) {
                // 近6月、近12月
                this.contractHalfYearTime = time;
                this.getContractHalfYear();
            }
        } else if (type == 'alr') {
            this.getAlrData();
        }
    }

    // 选择年度、月度
    handleAlready(type: string) {
        this.bgcColor[type] = true;
        if (type == 'week') {
            this.alrParams.weekFlag = true;
            this.alrParams.year = '';
            this.alrParams.month = '';
            // TODO  是否需要清除年月数据
            this.bgcColor.year = false;
            this.bgcColor.month = false;
            this.getAlrData();
        } else if (type == 'year' || type == 'month') {
            this.alrParams.weekFlag = false;
            this.bgcColor.week = false;
            console.log(this.alrParams[type], 'this.alrParams[type]');
            !this.alrParams[type] && (this.bgcColor[type] = false);
            this.getAlrData();
        }
    }

    // 年度或月度处理
    handleSelectField(value) {
        if (this.selectByField == value) {
            return;
        }
        this.selectByField = value;
        if (value == 'month') {
            this.alrParams.year = '';
        } else if (value == 'year') {
            this.alrParams.month = '';
        }
        this.getAlrData();
    }

    // 产品待办进程
    getProcessData() {
        api.listByFundOptStatus({ sponsor: this.currentUserCode })
            .then((res: any) => {
                if (res) {
                    for (let key in res) {
                        let obj = this.cards.find(item => item.name == key);
                        obj.data = res[key];
                    }
                }
            })
            .catch(err => {
                console.log(err, 'listByFundOptStatus');
            });
    }
    // 已办任务统计
    getAlrData() {
        api.dealedList({
            ...this.alrParams,
            weekFlag: this.alrParams.weekFlag ? '1' : '0',
            operator: this.currentUserCode,
            ...this.otherParams,
        })
            .then((res: any) => {
                this.alrData.data = res;
                console.log(res, 'res');
            })
            .catch(err => {
                console.log(err, 'dealedList');
            });
    }

    get otherParams() {
        let otherParams = {
            year: '',
            month: '',
        };
        if (!this.alrParams.weekFlag) {
            if (this.selectByField == 'year') {
                otherParams = {
                    year: this.alrParams.year,
                    month: '',
                };
            } else if (this.selectByField == 'month') {
                if (this.alrParams.month) {
                    let data = moment(this.alrParams.month, 'YYYYMM').format('YYYY-MM');
                    let values = data.split('-');
                    otherParams.year = values[0];
                    otherParams.month = values[1];
                }
            }
        }
        return otherParams;
    }

    // 合同/协议统计
    getContractHalfYear() {
        api.contractHalfYear({ monthOrYear: '-' + this.contractHalfYearTime })
            .then((res: any) => {
                // res = {
                //     legCount: 0,
                //     monthBefore: [
                //         '202206',
                //         '202207',
                //         '202208',
                //         '202209',
                //         '202210',
                //         '202211',
                //         '202212',
                //         '202301',
                //         '202302',
                //         '202303',
                //         '202304',
                //         '202305',
                //     ],
                //     products: ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '3', '0'],
                //     protocols: ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '2', '1'],
                //     totals: ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1'],
                // };
                this.contractData.data = {
                    products: res.products,
                    protocols: res.protocols,
                    totals: res.totals,
                };
                this.contractData.xData = res.monthBefore.map(item => {
                    return moment(item, 'YYYYMM').format('YYYY年MM月');
                });
                console.log(this.contractData, 'contractData');
            })
            .catch(err => {
                console.log(err, 'contractHalfYear');
            });
    }

    // 柱状图点击
    barClick(type: string, $event) {
        console.log(type, $event.params, '----------------------');
        const params = $event.params;
        if (type == 'contract-protocol') {
            let date = moment(params.xValue, 'YYYY年MM月').format('YYYY:MM');
            let values = date.split(':');
            // 查询条件参数
            let otherParams = {
                year: values[0],
                month: values[1],
            };
            this.$emit('tab-change', {
                name: 'task-detail',
                params: {
                    sponsor: this.currentUserCode,
                    contractType: params.contractType,
                    ...otherParams,
                },
            });
            // this.$emit('tab-change', { name: 'contract-detail', params: $event.params });
        } else if (type == 'already-statistics') {
            // 查询条件参数
            let otherParams = this.otherParams;

            this.$emit('tab-change', {
                name: 'task-detail',
                params: {
                    ...$event.params,
                    sponsor: params.status == '1' ? this.currentUserCode : this.alrParams.operator,
                    weekFlag: this.alrParams.weekFlag ? '1' : '0',
                    ...otherParams,
                },
            });
        } else {
            // 跳转到任务明细tab
            this.$emit('tab-change', {
                name: 'task-detail',
                params: { ...$event.params, sponsor: params.status == '1' ? this.currentUserCode : this.alrParams.operator },
            });
        }
        // else if (type == 'already-statistics') {
        //     // 跳转到任务明细tab
        // }
    }
}
</script>
<style lang="scss">
.content {
    min-height: 600px;
    height: 100%;
    .title {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 32px;
        line-height: 32px;
        overflow: hidden;
        // .bar-icon {
        //     width: 10px;
        //     height: 24px;
        //     background: #409eff;
        // }
        > span {
            padding-left: 8px;
            font-size: 14px;
            font-weight: bold;
        }

        .btn-operate {
            margin-right: 10px;
            text-align: right;
            .el-button {
                padding: 4px 2px;
                &:last-child {
                    margin-left: 4px;
                }
            }
            & > button {
                margin: 0 2px;

                & > span {
                    color: #333;
                }
            }
            & > .el-button--primary {
                background-color: #fff;
                & > span {
                    color: #ba926f;
                }
            }
        }
    }
    .charts {
        height: 100%;
        display: flex;
        flex-direction: column;
        background-color: #f2f3f5;
        .card-title {
            border-bottom: 1px solid #e5e5e5;
            height: 30px;
            background: #f7f8fc;
            line-height: 30px;
            padding: 0 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            .operate {
                height: 30px;
                line-height: 28px;
                .el-icon-date {
                    display: none;
                }

                .el-button {
                    padding: 4px 2px !important;
                    &:last-child {
                        margin-left: 4px;
                    }
                }
                .el-input--mini .el-input__inner {
                    height: 26px;
                }
                .el-input--prefix .el-input__inner {
                    padding-left: 10px;
                }
                .el-input--suffix .el-input__inner {
                    padding-right: 10px;
                }
                /deep/ .el-dropdown {
                    height: 13px !important;
                }
                & > span {
                    margin: 0 8px;
                }
                & > button {
                    margin: 0 2px;

                    & > span {
                        color: #333;
                    }
                }
                & > .el-button--primary {
                    background-color: #fff;
                    & > span {
                        color: #ba926f !important;
                        /deep/ .el-dropdown {
                            color: #ba926f !important;
                        }
                    }
                }
            }
        }
        .chart1-bar {
            height: calc(100% - 30px);
        }

        .charts-part1 {
            padding: 10px;
            background-color: #fff;
            display: grid;
            grid-template-columns: repeat(3, 1fr) 1.2fr;
            gap: 5px 10px;
            .charts-part1-content {
                height: calc(45vh - 20px);
                border: 1px solid #e5e5e5;
            }
            .already-statistics {
                height: 100%;

                .alr-chart {
                    // height: calc(100% - 41px);
                    // margin-top: 10px;
                    height: 100%;
                    border: 1px solid #e5e5e5;
                }
            }
        }

        .charts-part3 {
            height: calc(100% - 45px);
            // height: calc(100% - 40% - 100px);
        }

        .charts-part3 {
            // display: grid;
            // grid-template-columns: 56fr 44fr;
            // gap: 5px;
            .contract-protocol {
                height: 100%;
            }
        }
    }
}

.el-card .el-card__body {
    height: 100%;
    // height: calc(100% - 20px);
    padding: 0px !important;
}
.el-divider--horizontal {
    margin: 4px 0 !important;
}
</style>
